import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import { getLocal } from '@/utils/local'
import { auInfo } from '@/api/my'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/home/home.vue'),
    redirect: '/home/my',
    children: [
      {
        path: 'company',
        component: () => import('@/views/home/company/company.vue'),
        meta: {
          needTab: true
        }
      },
      {
        path: 'question',
        component: () => import('@/views/home/question/question.vue'),
        meta: {
          needLogin: true,
          needTab: true
        }
      },
      {
        path: 'find',
        component: () => import('@/views/home/find/find.vue'),
        meta: {
          needTab: true
        }
      },
      {
        path: 'shareList',
        component: () => import('@/views/home/find/shareList.vue'),
        meta: {
        }
      },
      {
        path: 'shareInfo/:id?',
        component: () => import('@/views/home/find/shareInfo.vue'),
        meta: {
        }
      },
      {
        path: 'my',
        component: () => import('@/views/home/my/my.vue'),
        meta: {
          needLogin: true,
          needTab: true
        }
      },
      {
        path: 'myInfo',
        component: () => import('@/views/home/my/myInfo.vue'),
        meta: {
          needLogin: true
        }
      },
      {
        path: 'editInfo',
        component: () => import('@/views/home/my/editInfo.vue'),
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 前置守卫
router.beforeEach((to, from, next) => {
  window.cancelAxios('', true)
  if (!to.meta.needLogin) {
    next()
  } else {
    if (store.state.isLogin) {
      next()
    } else {
      if (getLocal('token')) {
        auInfo().then(res => {
          console.log(res.data.data)
          store.commit('setUserInfo', res.data.data)
          store.commit('setIsLogin', true)
        })
        next()
      } else {
        console.log(to)
        // 准备要去的页面 路由传参
        next('/login?redirect=' + to.fullPath)
      }
    }
  }
})
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
